package com.cmwa.solution.business.customerEquity.estimate.controller;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.solution.base.controller.BaseController;
import com.cmwa.solution.base.entity.Page;
import com.cmwa.solution.base.entity.Result;
import com.cmwa.solution.base.entity.SearchParam;
import com.cmwa.solution.business.customerEquity.estimate.entity.EstimateInfoVo;
import com.cmwa.solution.business.customerEquity.estimate.service.EstimateInfoService;
import com.cmwa.solution.business.myHome.todo.service.TodoService;
import com.cmwa.solution.sys.attach.entity.AttachVo;
import com.cmwa.solution.sys.attach.service.AttachService;
import com.cmwa.solution.sys.dictionary.entity.DictionaryVo;
import com.cmwa.solution.sys.msg.util.StringUtil;
import com.cmwa.solution.utils.cached.DictionaryCached;

import net.sf.json.JSONArray;

/**
 * 估值表控制器
 * 
 * @author ex-zhengqq
 * @date 2019-01-23 13:34:46
 */
@Controller
@RequestMapping("/business/estimateInfo")
public class EstimateInfoController extends BaseController {

	private static final Log log = LogFactory.getLog(EstimateInfoController.class);
	
	private final static String JSP_PATH = "business/customerEquity/estimate/";
	
	@Resource
	private EstimateInfoService estimateInfoService;
	
	@Resource
	private AttachService attachService;
	
	@Resource
	private TodoService todoService;
	
	/**
	 * 跳转到列表页面
	 * @author ex-zhengqq
	 * @date 2019-01-23 13:34:46
	 * @param model
	 * @return
	 */
	@RequestMapping("/estimateInfoListView")
	public String estimateInfoListView(ModelMap model) {
		List<DictionaryVo> dicList = DictionaryCached.getDictionaryByRootType("TODO_STATUS");
		model.addAttribute("dicList",dicList);
		return JSP_PATH + "estimateList";
	}

	@RequestMapping("/estimateInfoListPage")
	@ResponseBody
	public Page<EstimateInfoVo> estimateInfoListPage(SearchParam param) {
		Page<EstimateInfoVo> list = estimateInfoService.estimateInfoListPage(param);
		return list;
	}
	
	/**
	 * 跳转到上传页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/estimateUpload")
	public String estimateUpload(ModelMap model,@RequestParam("estimateId") String estimateId,@RequestParam("type") String type,@RequestParam("reportTime") String reportTime,@RequestParam("prjsname") String prjsname,@RequestParam("prjCode") String prjCode){
		List<DictionaryVo> dicList = DictionaryCached.getDictionaryByType("ESTIMATE_TYPE", "ESTIMATE_TYPE", "ESTIMATE_TYPE");
		String attachListJson = null;
		if(StringUtils.isNotBlank(prjsname)) {
			model.addAttribute("prjsname", prjsname);
		}
		if(StringUtils.isNotBlank(reportTime)) {
			model.addAttribute("reportTime", reportTime);
		}
		if(StringUtils.isNotBlank(prjCode)) {
			model.addAttribute("prjCode", prjCode);
		}
		model.addAttribute("estimateId",estimateId);
		
		if(StringUtils.equalsIgnoreCase("estimateData", type)){
			//dicList = DictionaryCached.getDictionaryByType("ESTIMATE_DATA", "ESTIMATE_DATA", "ESTIMATE_DATA");
			model.addAttribute("attSource", "ESTIMATE_DATA");
			//查询对应的附件
			List<AttachVo> list = estimateInfoService.queryAttInfoById(estimateId,"ESTIMATE_DATA");
			if(!CollectionUtils.isEmpty(list)) {
				attachListJson = StringUtil.changeSpecialCharacter(JSONArray.fromObject(list).toString());
			}
			model.addAttribute("typeName", "估值材料上传");
			
		}else if(StringUtils.equalsIgnoreCase("estimateFile", type)){
			//dicList = DictionaryCached.getDictionaryByType("ESTIMATE_FILE", "ESTIMATE_FILE", "ESTIMATE_FILE");
			model.addAttribute("resourceSign","");
			model.addAttribute("attSource", "ESTIMATE_FILE");
			//查询对应的附件
			List<AttachVo> list = estimateInfoService.queryAttInfoById(estimateId,"ESTIMATE_FILE");
			if(!CollectionUtils.isEmpty(list)) {
				attachListJson = StringUtil.changeSpecialCharacter(JSONArray.fromObject(list).toString());
			}
			model.addAttribute("typeName", "估值文件上传");
		}
		model.addAttribute("attachList",attachListJson);
		model.addAttribute("dicList", dicList);
		return JSP_PATH + "uploadEstimate";
	}
	
	/**
	 * 保存估值表
	 * @param documentVo
	 * @return
	 */
	@RequestMapping("/saveEstimateInfo")
	public String saveEstimateInfo(EstimateInfoVo estimateInfoVo){
		//绑定附件-资源关联关系
		//String estimateId = estimateInfoVo.getEstimateId();//估值表ID
		String estimateId = estimateInfoVo.getEstimateId();
		String attSource = estimateInfoVo.getAttSource();
		String prjCode = estimateInfoVo.getPrjCode();
		String attIds = estimateInfoVo.getAttIds();
		//删除附件
		estimateInfoService.deleteAttach(estimateId,attSource);
		if(StringUtils.isNotBlank(prjCode) && StringUtils.isNotBlank(attIds)){//保存附件关联关系表
			estimateInfoService.addAttachRel(estimateInfoVo);
		}
		//估值表只做更新,先注释,未作联动
		//estimateInfoService.insertEstimateInfo(estimateInfoVo);
		//estimateInfoService.updateEstimateInfo(estimateInfoVo);
		return redirectSuccess();
	}
	
	/**
	 * 估值文件/材料下载（压缩包）,
	 * isBatch = N 单个
	 * isBatch = Y 批量
	 * @param addIdStr
	 * @param response
	 */
	@RequestMapping("/batchDownAttach")
	public void batchDownAttach(@RequestParam("estimateIds") String estimateIds, @RequestParam("esstimateType") String esstimateType, @RequestParam("isBatch") String isBatch,HttpServletRequest request,HttpServletResponse response) {
		log.info("估值业务下载，estimateIds：" + estimateIds + "，esstimateType：" + esstimateType+ "，isBatch：" + isBatch);
		OutputStream out = null;
//		List<String> attIds = null;
		String name = "";
		//判断前端传递过来的业务id和类型是否为空，
		if(StringUtils.isNotBlank(estimateIds) && StringUtils.isNotBlank(esstimateType)){
			SearchParam sp = new SearchParam();
			sp.getSp().put("esstimateType", esstimateType);
			if("Y".equals(isBatch)) {
				estimateIds = estimateInfoService.joinInSql(estimateIds);//特殊处理
				sp.getSp().put("inSQL", estimateIds);
				sp.getSp().put("isBatch", isBatch);
			}else {
				sp.getSp().put("estimateId", estimateIds);
			}
			if(StringUtils.equals("ESTIMATE_DATA", esstimateType)){
				name = "估值材料下载";
			}else if(StringUtils.equals("ESTIMATE_FILE", esstimateType)){
				name = "估值文件下载";
			}
			try {
				//实际存在系统中的附件
				List<AttachVo> attList = attachService.batchDownAttach(sp);
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/octet-stream;charset=UTF-8");
				response.setHeader("Content-Disposition",
						"Attachment;filename="+new String(name.getBytes("gb2312"), "ISO8859-1")+".zip");
				out = response.getOutputStream();
				estimateInfoService.downloadAttachZip(attList, out,isBatch);
				out.close();
			} catch (Exception e) {
				log.error("估值批量下载打包异常!,异常原因 ："+e);
			}
			if(StringUtils.equals("ESTIMATE_DATA", esstimateType)){
				name = "估值材料下载";
			}else if(StringUtils.equals("ESTIMATE_FILE", esstimateType)){
				name = "估值文件下载";
			}
			//根据类型查询相关的附件主键
			/*if(StringUtils.equals("ESTIMATE_DATA", esstimateType)){
				attIds = estimateInfoService.getAttachByIdEstimateData(estimateIds.split(","));
				name = "估值材料下载";
			}else if(StringUtils.equals("ESTIMATE_FILE", esstimateType)){
				attIds = estimateInfoService.getAttachByIdEstimateFile(estimateIds.split(","));
				name = "估值文件下载";
			}*/
			/*log.info("根据业务id查询出来的相关附件：" + attIds);
			if(CollectionUtils.isNotEmpty(attIds)) {
				//实际存在系统中的附件
				List<AttachVo> attList = attachService.findByIds(attIds.toArray(new String[attIds.size()]));
				attIds.clear();
				//根据业务查询出来的附件id，不一定存在系统中，所以需要做过滤
				for (AttachVo attachVo : attList) {
					attIds.add(attachVo.getAttId());
				}
				log.info("实际存在系统中的附件：" + attIds);
				//调用公共批量下载方法
				attachService.downloadAttachZip(Joiner.on(",").join(attIds), name, request, response);
			}*/
		}else {
			log.error("前端传递过来的业务id和类型不能为空");
		}
	}
	/**
	 * 批量下载（压缩包）首页批量下载
	 * @param addIdStr
	 * @param response
	 */
	@RequestMapping("/batchDownAttach2")
	public void batchDownAttach2(@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate, @RequestParam("esstimateType") String esstimateType,HttpServletRequest request,HttpServletResponse response) {
		log.info("估值业务批量下载，startDate：" + startDate + "，endDate：" + endDate+ "，esstimateType：" + esstimateType);
		OutputStream out = null;
		//判断前端传递过来的业务id和类型是否为空，
		if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)&& StringUtils.isNotBlank(esstimateType)){
			startDate = startDate.replaceAll("/", "-");
			endDate = endDate.replaceAll("/", "-");
			//根据类型查询相关的附件主键
			//attIds = estimateInfoService.getAttachByDateEstimateFile(startDate,endDate,esstimateType);
			
			//log.info("根据业务id查询出来的相关附件：" + attIds);
			SearchParam sp = new SearchParam();
			sp.getSp().put("startDate", startDate);
			sp.getSp().put("endDate", endDate);
			sp.getSp().put("esstimateType", esstimateType);
			//实际存在系统中的附件
			List<AttachVo> attList = attachService.batchDownAttach(sp);
			if(CollectionUtils.isNotEmpty(attList)) {
				//attachService.downloadAttachZip(Joiner.on(",").join(attIds), name, request, response);
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/octet-stream;charset=UTF-8");
					response.setHeader("Content-Disposition",
							"Attachment;filename="+new String("估值文件下载".getBytes("gb2312"), "ISO8859-1")+".zip");
					out = response.getOutputStream();
					estimateInfoService.downloadAttachZip(attList, out,"Y");
					out.close();
				} catch (Exception e) {
					log.error("估值批量下载打包异常!,异常原因 ："+e);
				}
			}
		}else {
			log.error("前端传递过来的业务id和类型不能为空");
		}
	}
	
	@RequestMapping("/checkAttach")
	@ResponseBody
	public Map<String,String> checkAttach(@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
		String attIds = "";
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
			startDate = startDate.replaceAll("/", "-");
			endDate = endDate.replaceAll("/", "-");
			attIds = estimateInfoService.getAttachByDateEstimateFile(startDate,endDate);
			//调用校验附件接口
			Result<Object> result = todoService.validateExistsFile("ESTIMATE", attIds, "output");
			if(result.isSuccess()) {
				map.put("Data", attIds);
				map.put("Status", "success");
			}else {
				map.put("Status", "error");
			}
		}else {
			map.put("Status", "error");
		}
		return map;
	}
}
